package org

import (
    "fmt"
	"time"
	"strconv"
	"strings"
	"encoding/json"
	"dhfshop/models/org"
	"dhfshop/controllers/base"
	"dhfshop/service/redisgo"
	"github.com/astaxie/beego/validation"
	"github.com/astaxie/beego"
)

// 公共-角色服务
type RoleController struct {
	base.BaseController
}

func (this *RoleController) List() {
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
    query["partner_id"] = strconv.FormatInt(partnerId, 10)
	l, cnt, err := org.GetAllRoles(query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount   int64         `json:"total_count"`
		Role        []*org.Role    `json:"roles"`
	}{TotalCount: cnt, Role: l}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *RoleController) Create() {
    var v org.Role
	this.ParseForm(&v)
	partnerITmp := this.Ctx.Input.GetData("curCompanyId").(int)    //不能是.(int64)
    v.PartnerId = int64(partnerITmp)
	//curUserId := this.Ctx.Input.GetData("curUserId").(int)
	valid := validation.Validation{}
	valid.Required(v.PartnerId, "partner_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	} 
	roleId, err := org.AddRole(&v); 
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(v.PermissionsStr) > 3 {
		err := json.Unmarshal([]byte(v.PermissionsStr), &v)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		for _, permission := range v.Permissions {
			permission.PartnerId = v.PartnerId
			permission.RoleId = roleId
		}
		if err := org.SavePermission(v.Permissions, int64(partnerITmp), roleId ); err != nil {
			this.ServeError(err.Error())
			return
		}
	}
    rsp := struct {
		RoleId    int64        `json:"role_id"`
	    Created   time.Time    `json:"created"`
	}{RoleId: v.RoleId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *RoleController) Put() {
    v := org.Role{}
    this.ParseForm(&v)
    partnerITmp := this.Ctx.Input.GetData("curCompanyId").(int)    //不能是.(int64)
    v.PartnerId = int64(partnerITmp)
    //curUserId := this.Ctx.Input.GetData("curUserId").(int)
    valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"is_sys","permissions"})
	if err != nil {
	   this.ServeError(err.Error())
		return
	}
	if err := org.UpdateRoleById(&v, updateFields...); err != nil {
	   this.ServeError(err.Error())
	    return
	}
	redisconn := redisgo.GetInstance()
	beego.Debug("RoleController Put partnerId,role_id:",v.PartnerId,v.RoleId)
	if users, err := org.GetSubUsers(v.RoleId, 0, 100); err == nil {
		for _, user := range users {
		   	beego.Debug("user user.UserId:", user.UserId)
			cacheKey := fmt.Sprintf("%s_%d_%d","permission_",v.RoleId,user.UserId)
	        err := redisconn.Del(cacheKey)
			if err != nil {
			   beego.Debug("redisconn.Del error:", err.Error())
			}
		}
	}
	if len(v.PermissionsStr) > 3 {
		err := json.Unmarshal([]byte(v.PermissionsStr), &v)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		for _, permission := range v.Permissions {
			permission.PartnerId = v.PartnerId
			permission.RoleId = v.RoleId
		}
		if err := org.SavePermission(v.Permissions, int64(partnerITmp), v.RoleId); err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	this.Data["json"] = v
	this.ServeJSON()
}

func (this *RoleController) Delete() {
    //companyId := this.Ctx.Input.GetData("curCompanyId").(int)
    //curUserId := this.Ctx.Input.GetData("curUserId").(int)
	IdStr := this.GetString("role_id")
	role_id, _ := strconv.ParseInt(IdStr, 10, 0)
	role, err := org.GetRoleByRoleId(role_id)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	}
	if role.IsSys {
	    this.ServeError("is_sys role can not delete")
	    return
	}
	if users, err := org.GetSubUsers(role_id, 0, 50); err == nil {
		var userIdArr []string
		if len(users) > 0 {
		   for _, user := range users {
			   userIdArr = append(userIdArr, strconv.FormatInt(user.UserId, 10))		   
			}
			userIds := strings.Join(userIdArr, ",")
			outMsg := fmt.Sprintf("此权限组绑定有用户%s,请先解除绑定", userIds)
			this.ServeError(outMsg)
			return
		}
	}	
	if err := org.DeleteRole(role_id); err != nil {
	    this.ServeError(err.Error())
	    return
	}
	rsp := struct {
		RoleId     int64       `json:"role_id"`
	    Modified   time.Time   `json:"modified"`
	}{RoleId:role_id, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}
